<?php
declare (strict_types=1);

namespace app\admin\controller\media;

use app\common\controller\BaseController;
use app\admin\model\media\Website as WebsiteModel;
use app\admin\model\media\Module as ModuleModel;
use app\admin\model\media\Article as ArticleModel;
use app\common\library\media\Crawler;
use think\exception\ValidateException;

class Module extends BaseController
{

    protected $noNeedRight = ['allModule', 'defaultRule'];

    /**
     * @var ModuleModel
     */
    protected $model;

    protected $modelValidate = true;
    /**
     * @var WebsiteModel
     */
    private $WebsiteModel;
    /**
     * @var ArticleModel
     */
    private $ArticleModel;

    public function initialize()
    {
        parent::initialize();

        $this->model = new ModuleModel;
        $this->WebsiteModel = new WebsiteModel;
        $this->ArticleModel = new ArticleModel;
    }

    /**
     * 查看
     * @param int $id
     */
    public function read($id = NULL)
    {
        $row = $this->model->with(['website'])->find($id);
        if (!$row) {
            return $this->error('未查询到任何记录');
        }
        $result = array('row' => $row);

        return $this->success('请求成功', $result);
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                //模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    try {
                        $this->validate($params, $validate);
                        $validateRes = true;
                    } catch (ValidateException $e) {
                        // 验证失败 输出错误信息
                        $validateRes = $e->getError();
                    }
                    if ($validateRes !== true) {
                        return $this->error($validateRes);
                    }
                }
                $config = json_decode($params['rules'], true);
                $crawler = new Crawler($config);
                $url = isset($config['url']) ? $config['url'] : $params['url'];
                $html = $crawler->getWebsiteHtml($url);
                $dataList = $crawler->getHtmlData();
                if (empty($dataList) || isset($dataList[0]['title']) == false) {
                    $this->error('采集规则无效');
                }
                $result = $this->model->save($params);
                if ($result !== false) {
                    $module = $this->model;
                    $this->ArticleModel->saveArticleList($dataList, $module);

                    $new = $params['website_id'];
                    $this->WebsiteModel->changeModuleNum($new);

                    //网站采集队列
                    $queueData = [
                        'module_id' => $this->model->id,
                    ];
                    $delay = $params['times'];
                    add_media_queue($queueData, $delay);
                    return $this->success('添加成功');
                } else {
                    return $this->error(lang('No rows were inserted'));
                }
            }
            return $this->error(lang('Parameter %s can not be empty', ''));
        }
    }


    /**
     * 编辑
     * @param null $id
     */
    public function edit($id = null)
    {
        $row = $this->model->find($id);
        if (!$row) {
            return $this->error(lang('No Results were found'));
        }
        if ($this->request->isPut()) {
            $params = $this->request->put();
            if ($params) {
                //模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    try {
                        $this->validate($params, $validate);
                        $validateRes = true;
                    } catch (ValidateException $e) {
                        // 验证失败 输出错误信息
                        $validateRes = $e->getError();
                    }
                    if ($validateRes !== true) {
                        return $this->error($validateRes);
                    }
                }
                $config = json_decode($params['rules'], true);
                $crawler = new Crawler($config);
                $url = isset($config['url']) ? $config['url'] : $params['url'];
                $html = $crawler->getWebsiteHtml($url);
                $dataList = $crawler->getHtmlData();
                if (empty($dataList) || isset($dataList[0]['title']) == false) {
                    $this->error('采集规则无效');
                }

                $old = $row['website_id'];
                $new = $params['website_id'];

                $result = $row->save($params);
                if ($result !== false) {
                    $this->WebsiteModel->changeModuleNum($new, $old);

                    return $this->success('编辑成功');
                } else {
                    return $this->error(lang('No rows were updated'));
                }
            }
            return $this->error(lang('Parameter %s can not be empty', ''));
        }
    }

    public function allModule()
    {
        $filter = $this->request->param();

        $where = function ($query) use ($filter) {
            if (isset($filter['website_id'])) {
                $query->where('website_id', '=', $filter['website_id']);
            }
        };
        $list = $this->model->field('id,name')
            ->where($where)
            ->where('status', '=', 1)
            ->order(['weigh' => 'desc', 'id' => 'asc'])
            ->select();

        return $this->success('请求成功', $list);
    }

    public function defaultRule()
    {
        $rules = [
            "url" => "",
            "method" => "GET",
            "accept" => "html",
            "async" => false,
            "timeout" => 5,
            "range" => "#list ul li",
            "rules" => [
                'title' => ['a', 'title'],
                'cover' => ['img', 'src'],
                'url' => ['a', 'href'],
                'time' => ['.time', 'text'],
                'extra' => ['.extra', 'text'],
                "full_url" => "",
            ],
            "params" => null,
        ];

        return $this->success('请求成功', $rules);
    }

}